/*
 * @Author: zhoulei0232
 * @Date: 2021-07-07 17:13:12
 * @LastEditTime: 2021-07-07 18:18:05
 * @LastEditors: zhoulei0232
 * @Description:
 */

/**
 * 过滤权限路由
 * @param routers 路由
 * @param roles 权限组
 */
export const filterAccesseRouter = (routers: any, roles: string[]) => {
  // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = routers.filter((router: any) => {
    // 是否权限管控
    if (checkPermission(router.meta && router.meta.permissions, roles)) {
      if (router.routes && router.routes.length) {
        router.routes = filterAccesseRouter(router.routes, roles);
      }
      return true;
    } else {
      return false;
    }
  });
  return accessedRouters;
};

/**
 * 过滤菜单路由
 * @param routers 路由
 * @param roles 权限组
 */
export const filterMenuRouter = (routers: any, role: string) => {
  // 遍历后台传来的路由字符串，转换为组件对象
  const menuRouters = routers.filter((router: any) => {
    let flag = router.roles.includes("AllMenu") || router.roles.includes(role);
    if (!flag) {
      return false;
    } else {
      if (router.subs && router.subs.length) {
        router.subs = filterMenuRouter(router.subs, role);
      } else if (router.subs && router.subs.length === 0) {
        return false;
      }
      return true;
    }
  });
  return menuRouters;
};

/**
 * 权限校验
 * @param value 权限
 * @param roles 权限组
 */
export const checkPermission = (value: any, roles: string[]) => {
  if (value && value instanceof Array && value.length > 0) {
    const permissionRoles = value;
    const hasPermission = roles.some((role) => {
      return permissionRoles.includes(role);
    });

    if (!hasPermission) {
      return false;
    }
    return true;
  } else {
    // 不设置权限默认显示
    return true;
  }
};
